import { ChangeEvent, useRef, useState } from "react";
import useRequest from "@/utils/useRequest";
import Modal,{ModalInstanceType} from "@/components/Modal";
import "./login.scss"
type LoginPropsType = {

}
type ResponseType =   {
  [key:string] : string,
  id:string,
  firstName:string,
  lastName:string,
}
function LoginPanel(props:LoginPropsType){
  const [account,setAccount] = useState("");
  const [pwd,setPwd] = useState("");
  const [agree,setAgree] = useState(false);
  const modalRef = useRef<ModalInstanceType>(null!);
  const handleChangeTel = (type:string,e:ChangeEvent<HTMLInputElement>) => {
    if(type === "tel"){
      setAccount(e.target.value);
    }else if(type === "pwd"){
      setPwd(e.target.value);
    }
   }
 
   const handleCheckAgree = (e:ChangeEvent<HTMLInputElement>) => {
     setAgree(e.target.checked);
   }
 
   const {loading, error,fetchData,cancelRequest} = useRequest<ResponseType>("/api/login",{data:{
     account,
     pwd,
     agree,
   },method:"POST"});
   
   const handleLogin = () => {
     if(!account) return modalRef.current.openModal("请输入账户")
     if(!pwd) return  modalRef.current.openModal("请输入密码")
     if(!agree) return modalRef.current.openModal("请阅读用户须知的条款");
     // fetchData()
     // cancelRequest();
     fetchData().then(res => {
         modalRef.current.openModal("登录成功");
         console.log(res.firstName);
     }).catch(err => {
       console.log(err);
     });
   }
    return <div className="login-form">
    <div className="login-form-content">
      <div className="form-item">
        <span className="form-item-title">手机号</span>
        <input value={account} className="form-item-content" type="text" placeholder="请输入手机号" onChange={(e) => handleChangeTel("tel",e)}></input>
      </div>
      <div className="form-item">
        <span className="form-item-title">密码</span>
        <input value={pwd}  className="form-item-content" type="password" placeholder="请输入密码" onChange={(e) => handleChangeTel("pwd",e)}></input>
      </div>
      <div className="form-login-btn" onTouchStart={handleLogin}>
                登录
      </div>
      <div className="form-user-known">
         <input  checked={agree} className="form-user-select" type="checkbox" onChange={handleCheckAgree}/>
         <p className="form-user-text">请阅读用户须知的条款</p>
      </div>
    </div>
    <Modal ref={modalRef}></Modal>
</div>;
}

export default LoginPanel;